/*
 * FreeModbus Libary: AVR Demo Application
 * Copyright (C) 2006 Christian Walter <wolti@sil.at>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * File: $Id: demo.c,v 1.7 2006/06/15 15:38:02 wolti Exp $
 */


#define F_CPU 16000000UL

/* ----------------------- AVR includes -------------------------------------*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <avr/eeprom.h>

/* ----------------------- Modbus includes ----------------------------------*/
#include "include/mb.h"
#include "include/mbport.h"
#include "board.h"

/* ----------------------- Defines ------------------------------------------*/
#define REG_INPUT_START 1000
#define REG_INPUT_NREGS 4

/* ----------------------- Static variables ---------------------------------*/
static USHORT   usRegInputStart = REG_INPUT_START;
static USHORT   usRegInputBuf[REG_INPUT_NREGS];

#define holdRegCount 10
#define holdRegStart 1000
static uint16_t	holdRegBuf[ holdRegCount ] = { 0x0001, 0x0002, 0x0004, 0x0008, 0x0010 };

const char version[] PROGMEM = {
	 __DATE__ " " __TIME__ 
};



uint8_t SerialNumber[] EEMEM = { "0000000000000000" };
uint16_t dummy EEMEM = 0xffff;


volatile char mcusr_mirror __attribute__ ((section (".noinit")));

void get_mcusr(void) \
__attribute__((naked)) \
__attribute__((section(".init3")));
void get_mcusr(void)
{
	mcusr_mirror = MCUSR;
	MCUSR = 0;
	wdt_disable();
}

extern volatile uint8_t SWITCH1;
extern volatile uint8_t SWITCH2;


/* ----------------------- Start implementation -----------------------------*/

int main( void )
{
    const UCHAR     ucSlaveID[] = { 0xAA, 0xBB, 0xCC };
    eMBErrorCode    eStatus;


	uint8_t MD = (MCUCSR | (1 << JTD));   // Forces compiler to use IN, OR plus two OUTs rather than two lots of IN/OR/OUTs
	MCUCSR = MD;                           // Turn on JTAG via code
	MCUCSR = MD;                           // Set bit twice as specified in datasheet

// 0 RS485DIR INT INT_RF 0 0 0 0
DDRE =  0b01000010;
PORTE = 0b00110000;

// PK2 PK1 00 00 SW1 SW2 00 00
DDRA = 0xC0;	// 0b11000000
PORTA = 0xC0;	// 0b11000000

//   O  O  O   I  I   I   I   I
//	L1 L2 L3 ID3 ID2 ID1 ID0 SW
DDRF = 0xE0;
PORTF = 0b00011111;


	

    eStatus = eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );

    eStatus = eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 );
    
	TCCR3B = _BV(WGM32) + _BV( CS31 ) +_BV(CS30);
	OCR3A  =  2499;		   // timer = 20 msec
	ETIMSK  = _BV(OCIE3A);	
	
	sei(  );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );

	usRegInputBuf[2]= 0xffee;
    for( ;; )
    {
        ( void )eMBPoll(  ); 
		_delay_ms(50 );

        /* Here we simply count the number of poll cycles. */
        usRegInputBuf[0] = (usRegInputBuf[0])++;
		holdRegBuf[2] = SWITCH1;
		holdRegBuf[3] = SWITCH2;
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
eMBErrorCode
eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs )
{
    eMBErrorCode    eStatus = MB_ENOERR;
    int             iRegIndex;

    if( ( usAddress >= REG_INPUT_START )
        && ( usAddress + usNRegs <= REG_INPUT_START + REG_INPUT_NREGS ) )
    {
        iRegIndex = ( int )( usAddress - usRegInputStart );
        while( usNRegs > 0 )
        {
            *pucRegBuffer++ =
                ( unsigned char )( usRegInputBuf[iRegIndex] >> 8 );
            *pucRegBuffer++ =
                ( unsigned char )( usRegInputBuf[iRegIndex] & 0xFF );
            iRegIndex++;
            usNRegs--;
        }
    }
    else
    {
        eStatus = MB_ENOREG;
    }

    return eStatus;
}


eMBErrorCode ReadHoldingReg( UCHAR *pucRegBuffer,  USHORT usAddress, USHORT usNRegs, eMBRegisterMode eMode )
{
eMBErrorCode    eStatus = MB_ENOERR;
int             iRegIndex;

	if( ( usAddress >= holdRegStart ) && ( usAddress + usNRegs <= holdRegStart + holdRegCount ) )
	{
		iRegIndex = ( int )( usAddress - holdRegStart );
		while( usNRegs > 0 )
		{
			*pucRegBuffer++ =
			( unsigned char )( holdRegBuf[iRegIndex] >> 8 );
			*pucRegBuffer++ =
			( unsigned char )( holdRegBuf[iRegIndex] & 0xFF );
			iRegIndex++;
			usNRegs--;
		}
	}
	else
	{
		eStatus = MB_ENOREG;
	}

	return eStatus;	
}

eMBErrorCode
eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs,
                 eMBRegisterMode eMode )
{
	if ( eMode == MB_REG_READ ) 
		return ReadHoldingReg( pucRegBuffer, usAddress, usNRegs, eMode);
	
	if ( ( eMode == MB_REG_WRITE )&& (usAddress == 1000) )
	{
		if ( *((uint16_t *)( pucRegBuffer )) )
		{
			holdRegBuf[1] = 0xff;
			PORTA |= 0x80;
			LED |= _BV( LED1 );
		}
		else
		{
			holdRegBuf[1] = 0x00;
			PORTA &= ~0x80;
			LED &= ~_BV( LED1 );
		}
		return MB_ENOERR;
	}
	else 
		return MB_ENOREG;
	
}



eMBErrorCode
eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNCoils,
               eMBRegisterMode eMode )
{
    
	return MB_ENOERR;
}

eMBErrorCode
eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNDiscrete )
{
    return MB_ENOREG;
}
